package com.atguigu.gulimail.search.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.common.to.es.SkuEsModel;
import com.atguigu.gulimail.search.conf.GulimailElsConfig;
import com.atguigu.gulimail.search.constant.EsConstant;
import com.atguigu.gulimail.search.service.ProductSaveService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Fengkai
 * @creat 2022/1/5
 */
@Service
@Slf4j
public class ProductSaveServiceImpl implements ProductSaveService {

    @Autowired
    RestHighLevelClient restHighLevelClient;
    //上架商品
    @Override
    public boolean produceStatusUp (List<SkuEsModel> skuEsModelList) throws IOException {
            //保存到es
        //1.给es中建立索引  建立好映射关系

        //给es中保存数据
//    BulkRequest bulkRequest, RequestOptions option
        BulkRequest bulkRequest = new BulkRequest();
        for (SkuEsModel esModel : skuEsModelList) {
            IndexRequest indexRequest = new IndexRequest(EsConstant.PRODUCT_INDEX);
            indexRequest.id(esModel.getSkuId().toString());
            String jsonString = JSONObject.toJSONString(esModel);
            indexRequest.source(jsonString, XContentType.JSON);
            bulkRequest.add(indexRequest);
        }
        String jsonString = JSONObject.toJSONString(bulkRequest);
        log.debug("请求es的信息,{}", jsonString);
        BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, GulimailElsConfig.COMMON_OPTIONS);

        //todo 错误处理
        boolean b = bulk.hasFailures();
        List<String> collect = Arrays.stream(bulk.getItems()).map(item -> {
            return item.getId();
        }).collect(Collectors.toList());
        log.info("商品上架成功:{}", collect);
        return  b;
    }
}
